package Utils;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {
	/**
	 * 后端数据序列json化
	 * @param name 放回给前端的数据名称
	 * @param obj 后台得到的数据
	 * @return json对象
	 */
	public JSONObject jsonObj(String name,Object obj) {
		JSONObject jsonObject = new JSONObject();
		// 先清空
		jsonObject.clear();
		// 传递到前端
		return jsonObject.fluentPut(name, obj);
	}
	/**
	 * 后端数据--->前端
	 * @param response 响应
	 * @param jsonObj json对象
	 * @throws IOException
	 */
	public void send(HttpServletResponse response,JSONObject jsonObj) throws IOException {
		PrintWriter out = response.getWriter();
		out.print(jsonObj.toString());// 可以传null
		out.flush();
		out.close();
	}
	
	
	/**
	 * 直接将传入的对象序列化为json，并写回客户端
	 * @param obj
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 */
	public void writeValue(Object obj,HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		response.setContentType("application/json;charset=utf-8");
		mapper.writeValue(response.getOutputStream(), obj);
	}
	/**
	 * 将传入的对象序列化json,返回
	 * @param obj
	 * @return
	 * @throws JsonProcessingException 
	 */
	public String writeValueAsString(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}
}
